import axios from 'axios'
import { saveAs } from 'file-saver'
import ToolElement from '@/tool/ToolElement';

const TOKEN_HEADER = 'ntd_token'

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000
})

// request拦截器
service.interceptors.request.use(config => {
  config.headers[TOKEN_HEADER] = 'ntd_fmhb'
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  let resData = res.data;
  // 未设置状态码则默认成功状态
  const code = resData.code || 200;
  // 获取错误信息
  const msg = resData.msg || '系统未知错误，请反馈给管理员'
  if (code === 401) {
    relogin();
    return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
  } 
  if (code !== 200) {
    ToolElement.msg(msg, 'error')
    return Promise.reject(new Error(msg))
  }
  return resData.data || resData.list || res;
},
  error => {
    handleError(error)
    return Promise.reject(error)
  }
)

function handleError({ message }) {
  if (message == "Network Error") {
    message = "后端接口连接异常"
  }
  else if (message.includes("timeout")) {
    message = "系统接口请求超时"
  }
  else if (message.includes("Request failed with status code")) {
    message = "系统接口" + message.substr(message.length - 3) + "异常"
  }
  ToolElement.msg('异常', message, 'error', 5 * 1000)
}

function relogin() {
  ToolElement.confirm('系统提示', '登录状态已过期，您可以继续留在该页面，或者重新登录', '重新登录').then(() => {
    useUserStore().logOut().then(() => {
      location.href = '/index';
    })
  })
}

export default service
